import router from '@/router'
import store from '@/store'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const userInfo = await store.dispatch('user/getUserInfo')
        const filterRouter = asyncRoutes.filter(item => {
          return userInfo.roles.menus.some(value => {
            return value === item.name
          })
        })
        // addRoutes进行动态路由添加
        // 进行累计增加
        router.addRoutes([...filterRouter, { path: '*', redirect: '/404', hidden: true }])
        store.commit('user/setMenu', filterRouter)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  nprogress.done()
})

router.afterEach(() => {
  nprogress.done()
})
